--Tracker config
local TARGET_MAP = "MAP40"
local TRASHDOWN_TIME = 210 * TICRATE
local DIST_DETECTION = 2800 * FRACUNIT 
local DIST_PROCHE = 700 * FRACUNIT    

local function get3DDist(mo1, mo2)
    local dist2D = R_PointToDist2(mo1.x, mo1.y, mo2.x, mo2.y)
    return R_PointToDist2(0, 0, dist2D, mo1.z - mo2.z)
end

-- Tracker display

addHook("HUD", function(v, player, camera)

-- Le code doit être EXCLUSIF a Trashbag Temple, sinon on va se plaindre

    if G_BuildMapName(gamemap) ~= TARGET_MAP then return end
    if leveltime < TRASHDOWN_TIME then return end
    if not (gametype == GT_TAG or gametype == GT_HIDEANDSEEK) then return end
    
    if not (player.pflags & PF_TAGIT) then return end
    if not (player.mo and player.mo.health > 0) then return end 

    local cibleLePlusProche = nil
    local distanceMin = nil

    for autre in players.iterate do
        if autre == player then continue end
        if not (autre.mo and autre.mo.health > 0) then continue end 
        if autre.spectator then continue end
        if (autre.pflags & PF_TAGIT) then continue end

        local dist = get3DDist(player.mo, autre.mo)
        if distanceMin == nil or dist < distanceMin then
            distanceMin = dist
            cibleLePlusProche = autre
        end
    end

    local nomPatch = "TRACKR1"
    local couleurCible = nil

    if cibleLePlusProche and distanceMin <= DIST_DETECTION then
        couleurCible = cibleLePlusProche.skincolor
        if distanceMin <= DIST_PROCHE then
            nomPatch = "TRACKR3" 
        else
            nomPatch = "TRACKR2" 
        end
    end

    -- 4. la position du tracker
	
    local patch = v.cachePatch(nomPatch)
    
    if couleurCible then
        local colormap = v.getColormap(TC_DEFAULT, couleurCible)
        -- V_SNAPTOBOTTOM + V_PERPLAYER pour s'assurer que ça reste en bas au centre
        v.draw(0, 0, patch, V_SNAPTOBOTTOM|V_PERPLAYER, colormap)
    else
        v.draw(0, 0, patch, V_SNAPTOBOTTOM|V_PERPLAYER)
    end

end, "game")